//
//  GGContractABUIViewController.m
//  ggtool
//
//  Created by engfei on 2017/5/4.
//  Copyright © 2017年 GaiGai. All rights reserved.
//

#import "GGContactABUIViewController.h"
#import <AddressBookUI/AddressBookUI.h>
//#import <ContactsUI/ContactsUI.h>

#define SYSTEM_VERSION [[UIDevice currentDevice].systemVersion floatValue]

@interface GGContactABUIViewController ()<ABPeoplePickerNavigationControllerDelegate, ABPersonViewControllerDelegate, ABNewPersonViewControllerDelegate, ABUnknownPersonViewControllerDelegate>

@end

@implementation GGContactABUIViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    float num = [[UIDevice currentDevice].systemVersion floatValue];
    NSLog(@"%f", num);
    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    [self address];
}

- (void)address {
    
    // 单选和多选,有实现的代理方法决定
    ABPeoplePickerNavigationController *pickerVC = [[ABPeoplePickerNavigationController alloc] init];
    pickerVC.peoplePickerDelegate = self;
    [self presentViewController:pickerVC animated:YES completion:nil];
    
    
////    ABPersonViewController does not support subclassing in iOS 7.0 and later. A nil instance will be returned.
//    ABPersonViewController *personVC = [[ABPersonViewController alloc] init];
//    personVC.personViewDelegate = self;
//    [self presentViewController:personVC animated:YES completion:nil];

 
    
//    // 添加联系人, 没有保存按钮
//    ABNewPersonViewController *newPersonVC = [[ABNewPersonViewController alloc] init];
//    newPersonVC.newPersonViewDelegate = self;
//    [self presentViewController:newPersonVC animated:YES completion:nil];
    
//    ABUnknownPersonViewController *unknownVC = [[ABUnknownPersonViewController alloc] init];
//    unknownVC.unknownPersonViewDelegate = self;
//    [self presentViewController:unknownVC animated:YES completion:nil];

}


#pragma mark - ABPeoplePickerNavigationControllerDelegate
//
//// ABRecordRef 联系人属性的集合
//// ABAddressBookRef 通讯录操作对象
//
// Called after a person has been selected by the user.
// 选择一个用户的时候回调
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person {
    
    NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    
    NSLog(@"firstName = %@, lastName = %@", firstName, lastName);
    
    
    
    /*** 另外一种写法 ***/
    // 取出联系人的姓名数据
    CFStringRef firstName01 = ABRecordCopyValue(person, kABPersonFirstNameProperty);
    CFStringRef lastName01 = ABRecordCopyValue(person, kABPersonLastNameProperty);
    // 将CoreFoundation的字符串, 转化为OC的字符串, 并且转移内存管理权
    NSString *first = CFBridgingRelease(firstName01);
    NSString *last = CFBridgingRelease(lastName01);
    
    NSLog(@"另外一种转换 = first = %@, last = %@", first, last);
    
    // 取出电话的数据
    ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex count = ABMultiValueGetCount(multi);
    
    for (int i = 0; i < count; i++) {
        NSString *label = (__bridge_transfer NSString *)ABMultiValueCopyLabelAtIndex(multi, i);
        NSString *phone = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(multi, i);
        NSLog(@"%@---%@", label, phone);
    }
    
    
}
//
//// Called after a property has been selected by the user.
//// 选择一个属性时回调
//- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
//    
//    
//}
//
//// Called after the user has pressed cancel.
//// 点击取消时回调
//- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker {
//    
//    
//}


//// Deprecated, use predicateForSelectionOfPerson and/or -peoplePickerNavigationController:didSelectPerson: instead.
//
//- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person {
//    
//    return YES;
//}

//// Deprecated, use predicateForSelectionOfProperty and/or -peoplePickerNavigationController:didSelectPerson:property:identifier: instead.
//- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
//    
//    return YES;
//}


#pragma mark - ABPersonViewControllerDelegate
// Called when the user selects an individual value in the Person view, identifier will be kABMultiValueInvalidIdentifier if a single value property was selected.
// Return NO if you do not want anything to be done or if you are handling the actions yourself.
// Return YES if you want the ABPersonViewController to perform its default action.
// 添加联系人
- (BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    TFFunc;
    return YES;
}


#pragma mark - ABNewPersonViewControllerDelegate


// Called when the user selects Save or Cancel. If the new person was saved, person will be
// a valid person that was saved into the Address Book. Otherwise, person will be NULL.
// It is up to the delegate to dismiss the view controller.
//完成新增（点击取消和完成按钮时调用）,注意这里不用做实际的通讯录增加工作，此代理方法调用时已经完成新增，当保存成功的时候参数中得person会返回保存的记录，如果点击取消person为NULL  
- (void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(nullable ABRecordRef)person {
    
    TFFunc;
}


#pragma mark - ABUnknownPersonViewControllerDelegate
// Called when picking has completed.  If picking was canceled, 'person' will be NULL.
// Otherwise, person will be either a non-NULL resolved contact, or newly created and
// saved contact, in both cases, person will be a valid contact in the Address Book.
// It is up to the delegate to dismiss the view controller.
- (void)unknownPersonViewController:(ABUnknownPersonViewController *)unknownCardViewController didResolveToPerson:(nullable ABRecordRef)person {
    
    TFFunc;
}

// Called when the user selects an individual value in the unknown person view, identifier will be kABMultiValueInvalidIdentifier if a single value property was selected.
// Return NO if you do not want anything to be done or if you are handling the actions yourself.
// Return YES if you want the ABUnknownPersonViewController to perform its default action.
- (BOOL)unknownPersonViewController:(ABUnknownPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier __OSX_AVAILABLE_STARTING(__MAC_NA, __IPHONE_3_0) {
    
    TFFunc;
    return YES;
}



//
////编辑联系人
//- (void)editButtonAction{
//    if (SYSTEM_VERSION  <9.0f) {
//        NSLog(@"EDIT ios7,8");
//        //ABPersonViewController *personController=[[ABPersonViewController alloc]init];
//        ABNewPersonViewController *personController = [[ABNewPersonViewController alloc] init];
//        //设置联系人
//        ABAddressBookRef addressBook=ABAddressBookCreateWithOptions(NULL, NULL);
//        ABRecordRef recordRef= ABAddressBookGetPersonWithRecordID(addressBook, currentContactPerson.recordID);//取得id为1的联系人记录
//        personController.displayedPerson=recordRef;
//        //设置代理
//        // personController.personViewDelegate=self;
//        
//        personController.newPersonViewDelegate = self;
//        //设置其他属性
//        //personController.allowsActions=YES;//是否显示发送信息、共享联系人等按钮
//        //personController.allowsEditing=YES;//允许编辑
//        //    personController.displayedProperties=@[@(kABPersonFirstNameProperty),@(kABPersonLastNameProperty)];//显示的联系人属性信息,默认显示所有信息
//        
//        personController.navigationItem.title = @"编辑联系人";
//        //使用导航控制器包装
//        UINavigationController *navigationController=[[UINavigationController alloc]initWithRootViewController:personController];
//        [self presentViewController:navigationController animated:YES completion:nil];
//        
//    }else{
//        NSLog(@"EDIT ios9");
//        CNContactStore *store = [[CNContactStore alloc] init];
//        // 3.2.创建联系人的请求对象
//        // keys决定这次要获取哪些信息,比如姓名/电话
//        CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:@[CNContactIdentifierKey, CNContactEmailAddressesKey, CNContactBirthdayKey, CNContactImageDataKey, CNContactPhoneNumbersKey, [CNContactFormatter descriptorForRequiredKeysForStyle:CNContactFormatterStyleFullName], [CNContactViewController descriptorForRequiredKeys]]];
//        //CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:fetchKeys];
//        
//        // 3.3.请求联系人
//        NSError *error = nil;
//        [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {
//            // stop是决定是否要停止
//            // 1.获取姓名
//            NSString *firstname = contact.givenName;
//            NSString *lastname = contact.familyName;
//            //NSLog(@"%@ %@", firstname, lastname);
//            
//            //通过姓名寻找联系人
//            NSMutableString *fullName= [[NSMutableString alloc] init];
//            if (lastname!=nil||lastname.length>0) {
//                [fullName appendString:lastname];
//            }
//            if (firstname!=nil||firstname.length>0) {
//                [fullName appendString:firstname];
//            }
//            
//            if ([fullName isEqualToString:currentContactPerson.fullName]) {
//                *stop = YES;
//                //CNContactViewController *controller = [CNContactViewController viewControllerForContact:contact];
//                CNContactViewController *controller = [CNContactViewController viewControllerForNewContact:contact];
//                controller.navigationItem.title = @"";
//                //代理内容根据自己需要实现
//                controller.delegate = self;
//                //4.跳转
//                UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:controller];
//                [self presentViewController:navigation animated:YES completion:^{
//                }];
//            }
//            
//            
//            // 2.获取电话号码
//            NSArray *phones = contact.phoneNumbers;
//            
//            // 3.遍历电话号码
//            for (CNLabeledValue *labelValue in phones) {
//                CNPhoneNumber *phoneNumber = labelValue.value;
//                //  NSLog(@"%@ %@", phoneNumber.stringValue, labelValue.label);
//            }
//        }];
//        /*
//         CNContactViewController *controller = [CNContactViewController viewControllerForNewContact:contact];
//         //代理内容根据自己需要实现
//         controller.delegate = self;
//         //4.跳转
//         UINavigationController *navigation = [[UINavigationController alloc] initWithRootViewController:controller];
//         [self presentViewController:navigation animated:YES completion:^{
//         
//         }];
//         */
//    }
//    
//    
//}
//
////ios7,8
//#pragma mark - ABPersonViewController代理方法
////选择一个人员属性后触发，返回值YES表示触发默认行为操作，否则执行代理中自定义的操作
//-(BOOL)personViewController:(ABPersonViewController *)personViewController shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
//    
//    return YES;
//    /*
//     if (person) {
//     NSLog(@"选择了属性：%i，值：%@.",property,(__bridge NSString *)ABRecordCopyValue(person, property));
//     }
//     return NO;
//     */
//}
//
////ios7,8
//#pragma mark - ABNewPersonViewController代理方法
////完成新增（点击取消和完成按钮时调用）,注意这里不用做实际的通讯录增加工作，此代理方法调用时已经完成新增，当保存成功的时候参数中得person会返回保存的记录，如果点击取消person为NULL
//-(void)newPersonViewController:(ABNewPersonViewController *)newPersonView didCompleteWithNewPerson:(ABRecordRef)person{
//    //如果有联系人信息
//    if (person) {
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            [self loadPerson];
//            dispatch_sync(dispatch_get_main_queue(), ^{
//                //刷新列表
//                [contactTableView reloadData];
//            });
//        });
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDialContact" object:nil];
//        NSLog(@"%@ 信息保存成功.",(__bridge NSString *)(ABRecordCopyCompositeName(person)));
//    }else{
//        NSLog(@"点击了取消.");
//    }
//    //关闭模态视图窗口
//    [self dismissViewControllerAnimated:YES completion:nil];
//    
//}
////iOS9
//#pragma mark - CNContactViewControllerDelegate
//- (void)contactViewController:(CNContactViewController *)viewController didCompleteWithContact:(nullable CNContact *)contact{
//    if(contact){
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            [self loadPerson];
//            dispatch_sync(dispatch_get_main_queue(), ^{
//                //刷新列表
//                [contactTableView reloadData];
//            });
//        });
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshDialContact" object:nil];
//    }
//    [viewController dismissViewControllerAnimated:YES completion:^{
//        
//    }];
//}
//
//
//- (void)loadPerson {
//    
//}



@end
